<?php
/**
 * @package PWE.modele
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_post extends modele{
    protected static $_table = 'post';
    public $type = 'post';
    private $_id;
    private $_user;
    private $_user_id;
    private $_title;
    private $_content;
    private $_summary='';
    private $_custom_vars = null;
    private $_date_crea;
    

    function __construct($id=null){
        if($id!==null){
            $this->_id = $id;
            $this->_constructObject();
        }
    }
    
    private function _constructObject(){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.* ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        $sqlQuery .= 'WHERE t.id='.$this->_id.' ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = $this->_getOneResult($sqlQuery);
        $this->_title = $datas['title'];
        $this->_user_id = $datas['user_id'];
        $this->_content =  $datas['content'];
        $this->_summary =  $datas['summary'];
        $this->_custom_vars = $datas['custom_vars'];
        $this->_date_crea = $datas['date_crea'];
    }
    public function getId(){
        return $this->_id;
    }
    public function setId($id=0){
        $this->_id = $id;
    }
    public function getDateCrea($input=false){
        return $this->_date_crea;
    }
    /**
     * 
     * @return \modele_user|null
     */
    public function getUser(){
        if(isset($this->_user)){
            return $this->_user;
        }elseif(isset($this->_user_id)){
            $user = new modele_user($this->_user_id);
            return $user;
        }else{
            return null;
        }
    }
    public function getAuteur($input=false){
        $user = $this->getUser();
        return ($user!==null)?$user->getPrenom($input).' '.$user->getNom($input):'';
    }
    public function getAuteurLevel($input=false){
        $user = $this->getUser();
        return $user->getLevelNom($input);
    }
    public function getTitle($input=false){
        if($input)return $this->inputFormat($this->_title);
        return $this->outputFormat($this->_title);
    }
    public function getContent($input=false){
        if($input)return $this->inputFormat($this->_content);
        return $this->outputFormat($this->_content);
    }
    public function getSummary($input=false,$limit=2000){
        if($this->_summary!==null&&$this->_summary!==''){
            $summary = ($input)?$this->inputFormat($this->_summary):$this->outputFormat($this->_summary);
        }else{
            $summary = $this->generateSummary($this->getContent(),$input,$limit);
        }
        return $summary;
    }
    /**
     * générer un résumé du contenu
     * @param string $string
     * @param int $limit
     */
    public function generateSummary($string,$input=false,$limit=2000){
        $retour = substr(tools_convert::cleanString($string), 0,$limit);
        return ($input)?$this->inputFormat($retour):$this->outputFormat($retour);
    }
    
    public function getCustomVars($input=false){
        $retour = array();
        if($this->_custom_vars != null){
            $customVars = unserialize($this->_custom_vars);
            if(count($customVars)>0){
                foreach($customVars as $k=>$v){
                    if(!$input){
                        $retour[$k]=stripslashes($this->outputFormat($v));
                        
                    }else{
                        $retour[$k]=stripslashes($v);
                    }
                }
            }
        }
        return $retour;
    }
    /**
     * retourne la valeur d'une custom var
     * @param string $var
     * @param boolean $input
     * @return string|null
     */
    public function getCustomVar($var,$input=false){
        $vars = $this->getCustomVars($input);
        return (isset($vars[$var]))?$vars[$var]:null;
    }
    
    public function setCustomVar($name,$value){
        $customVars = $this->getCustomVars();
        $customVars[$name] = $value;
        $toSerialize = array();
        foreach ($customVars as $k=>$v){
            $toSerialize[$k] = str_replace(array("\n","\r","\\","'"),array('','','',"&#39;"),$this->inputFormat($v));
        }
        $this->_custom_vars = serialize($toSerialize);
        $sql = 'UPDATE '.self::getTable()." SET custom_vars='".$this->_custom_vars."'";
        $sql .= 'WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sql,false);
        return true;
    }
    
    public function getDatas($input=false){
        $datas = array(
            'id'=>$this->_id,
            'auteur'=>$this->getAuteur($input),
            'date_crea'=>$this->getDateCrea($input),
            'title'=>$this->getTitle($input),
            'content'=>$this->getContent($input),
            'custom_vars'=>$this->getCustomVars($input),
            'summary'=>$this->getSummary($input)
        );
        return $datas;
    }
    public function setDatas($datas){
        foreach($datas as $k=>$v){
            if(substr($k, 0, 1) !== '_') $k = '_'.$k;
            if($k != '_id' && property_exists('modele_post',$k)){
                if($k=='_custom_vars'){
                    if(count($v)>0){
                        $cv = $this->getCustomVars();
                        foreach($v as $sk=>$sv){
                            $cv[$sk]=str_replace(array("\n","\r","\\","'"),array('','','',"&#39;"),$this->inputFormat($sv));
                        }
                        $this->$k=serialize($cv);
                    }
                }else{
                    $this->$k = $v;
                }
            }
        }
        return true;
    }
    public function save(){
        $user = modele_user::getConnectedAdmin();
        // message
        $sqlQueryPost = 'INSERT INTO '.self::getTable().' ';
        $sqlQueryPost .= '(title,user_id,content,summary,custom_vars,date_crea) ';
        $sqlQueryPost .= 'VALUES (';
        $sqlQueryPost .= '"'.$this->getTitle(true).'", ';
        $sqlQueryPost .= $user->getId().', ';
        $sqlQueryPost .= '"'.$this->getContent(true).'", ';
        //$sqlQueryPost .= ($this->_summary!=='')?'"'.$this->getSummary(true).'", ':'"", ';
        $sqlQueryPost .= '"'.$this->inputFormat($this->_summary).'", ';
        $sqlQueryPost .= "'".$this->_custom_vars."', ";
        $sqlQueryPost .= '"'.date("Y-m-d H:i:s").'")';
        
        bdd_sql::doSql($sqlQueryPost,false);
        $this->setId(bdd_sql::getLastInsertId());
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    public function update(){
        // message
        $sqlQueryPost = 'UPDATE '.self::getTable().' SET ';
        $sqlQueryPost .= '`title`="'.$this->getTitle(true).'", ';
        $sqlQueryPost .= "custom_vars='".$this->_custom_vars."', ";
        //$sqlQueryPost .= ($this->_summary!=='')?'summary="'.$this->getSummary(true).'", ':'';
        $sqlQueryPost .= 'summary="'.$this->inputFormat($this->_summary).'", ';
        $sqlQueryPost .= 'content="'.$this->getContent(true).'" ';
        $sqlQueryPost .= 'WHERE id='.$this->getId().' LIMIT 1';
        
        bdd_sql::doSql($sqlQueryPost,false);
        
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    
    public function delete() {
        $sqlDelete = 'DELETE FROM '.self::getTable().' WHERE id='.$this->_id;
        bdd_sql::doSql($sqlDelete,false);

        return array('success'=>true,'datas'=>array());
    }
    /* methodes statiques */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
}
?>